<template>
  <el-upload
    :disabled="disabled"
    ref="uploadRef"
    :accept="acceptTypes"
    :headers="uploadHeaders"
    :on-remove="handleRemove"
    :file-list="fileArr"
    :on-preview="handlePreview"
    :on-change="changeFile"
    :auto-upload="false"
  >
    <el-button
      size="small"
      type="primary"
      :disabled="hideText || (maxLen !== 0 && files.length === maxLen)"
      >点击上传</el-button
    >
    <slot name="temp"></slot>
    <template #tip v-if="!hideText">
      <div class="el-upload__tip" v-if="maxLen !== 0">
        {{ files.length }} / {{ maxLen }}
      </div>
      <div class="el-upload__tip">
        {{
          `支持上传 ${
            formatRestriction.length > 0
              ? formatRestriction.join("、")
              : "doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等"
          } 格式文件,文件大小不得大于${sizeRestriction}M。`
        }}
      </div>
    </template>
  </el-upload>
  <el-progress v-if="processLoadding" :percentage="loadProgress" />
</template>
<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import NotifMessage from "/@/utils/message/notification";
import {
  handleError,
  beforeAvatarUpload,
  acceptTypes,
  uploadHeaders
} from "/@/utils/file";
import { importFileForEcm } from "/@/utils/ecm";
import { docTypesMatch } from "/@/views/projectsS/document/engineering/types";
export default defineComponent({
  name: "ecmUpload",
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    hideText: {
      type: Boolean,
      default: false
    },
    files: {
      type: Array,
      default: () => []
    },
    formatRestriction: {
      type: Array,
      default: () => []
    },
    sizeRestriction: {
      type: Number,
      default: 20
    },
    maxLen: {
      type: Number,
      default: 0
    }
  },

  emits: ["setFile"],
  setup(props, { emit }) {
    let index = 0;
    let fileArr = ref([]);
    const uploadRef = ref(null);
    const defaultFileList = ref<any>([]);
    const loadProgress = ref(0);
    const processLoadding = ref(false);
    let docId = import.meta.env.VITE_APP_ECM_DOCID;

    watch(
      () => props.files,
      () => {
        fileArr.value = props.files || [];
      }
    );

    const beforeUpload = (file: any) => {
      const type = file.name
        .substring(file.name.lastIndexOf(".") + 1)
        .toLocaleLowerCase();
      if (
        props.formatRestriction.length > 0 &&
        !props.formatRestriction.includes(type)
      ) {
        NotifMessage.warning(
          `请上传${props.formatRestriction.join("、")}格式!`
        );
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < props.sizeRestriction;

      if (!isLt2M) {
        NotifMessage.warning(`文件大小不能超过${props.sizeRestriction}M!`);
        return false;
      }

      return true;
    };

    const changeFile = async file => {
      const bool = beforeUpload(file);
      if (!bool) {
        fileArr.value = [...fileArr.value];
        return;
      }
      try {
        processLoadding.value = true;
        loadProgress.value = 10;
        const res: any = await importFileForEcm(docId, file.raw);
        const arr = file.name.split(".");
        let fileObj = {
          name: file.name,
          fileName: file.name,
          uuidFile: res.docid,
          fileSize: file.size,
          fileType: docTypesMatch(arr[arr.length - 1]).key,
          url: res.rev
        };
        loadProgress.value = 100;
        fileArr.value.push(fileObj);
        let timer = setTimeout(() => {
          clearTimeout(timer);
          timer = null;
          processLoadding.value = false;
          emit("setFile", fileArr.value);
        }, 500);
      } catch (e) {
        NotifMessage.error(e?.message);
        processLoadding.value = false;
        fileArr.value = [...fileArr.value];
        emit("setFile", fileArr.value);
      }
    };

    const handleRemove = file => {
      fileArr.value = fileArr.value.filter(item => {
        return item.name !== file.name;
      });
      emit("setFile", fileArr.value);
    };

    const handlePreview = (item: any) => {
      if (item.response) {
        // let el=item.response.data
        window.open(
          `${location.origin}${location.pathname}#/preview?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
        );
      } else {
        let el = fileArr.value.find(a => a.name == item.name);
        window.open(
          `${location.origin}${location.pathname}#/preview?uuidFile=${el.uuidFile}&fileName=${el.fileName}`
        );
      }
    };

    watch(
      () => props.files,
      (val, oldVal) => {
        if (val && val.length > 0 && index === 0) {
          index++;
          if (oldVal == null || oldVal.length === 0) {
            fileArr.value = JSON.parse(JSON.stringify(val));
            defaultFileList.value = val;
          }
        }
      },
      {
        immediate: true
      }
    );

    return {
      loadProgress,
      processLoadding,
      uploadRef,
      changeFile,
      defaultFileList,
      handlePreview,
      handleRemove,
      handleError,
      beforeAvatarUpload,
      beforeUpload,
      acceptTypes,
      uploadHeaders,
      fileArr
    };
  }
});
</script>
